package com.jy.modules.cims.component.sysAssist.BQRunner;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.jy.modules.cims.common.CimsConstant;

/**
 * 多任务并发执行器(阻塞队列模式)
 * <b>类名称：</b>MultiTaskBQRunner <br/>
 * <b>类描述：</b><br/>
 * <b>创建人：</b>chenguixue<br/>
 * <b>修改人：</b><br/>
 * <b>修改时间：</b>2015-4-9 下午5:49:48<br/>
 * <b>修改备注：</b><br/>
 * <b>版本信息：</b>v1.0.0<br/>
 */
public class MultiTaskBQRunner {
	private static final Logger logger =  LoggerFactory.getLogger(MultiTaskBQRunner.class);
	private ExecutorService service = null;
	private BlockingQueue<TaskBQNodeCfg> taskQueue = new LinkedBlockingQueue<TaskBQNodeCfg>(); 
	
	public void start() {
		logger.info("初始化多任务执行器！");
		ExecutorService service = Executors.newCachedThreadPool();  
        for(int i = 0; i < CimsConstant.MULTIRUNNER_INIT_THREAD_NUM; i++) {
            service.submit(new TaskBQConsumer(this));  
        }        
        logger.info("多任务执行器启动完成！");
	}
	public void stop() {
		if(null != service)
			service.shutdownNow(); 
		logger.info("多任务执行器关闭！");
	}
	public void addTask(TaskBQNodeCfg cfg) {
		try {
			taskQueue.put(cfg);
		} catch (InterruptedException e) {
			e.printStackTrace();
			logger.error("多任务并发执行器增加任务" + cfg + "失败");
		}
	}
	public int getTaskNum() {
		return taskQueue.size();
	} 
    public void consume() throws Exception{ 
    	TaskBQNodeCfg cfg = taskQueue.take();  
    	TaskBQNodeRunner taskBQNodeRunner = cfg.getTaskBQNodeRunner();
		taskBQNodeRunner.init(cfg);
		taskBQNodeRunner.run();
    }
}
